* When wfMsg*NoTrans() was called the message cache transformation was
[lhc/web/wiklou.git] / includes / GlobalFunctions.php
1 <?php
2
3 /**
4 * Global functions used everywhere
5 * @package MediaWiki
6 */
7
8 /**
9 * Some globals and requires needed
10 */
11
12 /**
13 * Total number of articles
14 * @global integer $wgNumberOfArticles
15 */
16 $wgNumberOfArticles = -1; # Unset
17 /**
18 * Total number of views
19 * @global integer $wgTotalViews
20 */
21 $wgTotalViews = -1;
22 /**
23 * Total number of edits
24 * @global integer $wgTotalEdits
25 */
26 $wgTotalEdits = -1;
27
28
29 require_once( 'DatabaseFunctions.php' );
30 require_once( 'UpdateClasses.php' );
31 require_once( 'LogPage.php' );
32 require_once( 'normal/UtfNormalUtil.php' );
33
34 /**
35 * Compatibility functions
36 * PHP <4.3.x is not actively supported; 4.1.x and 4.2.x might or might not work.
37 * <4.1.x will not work, as we use a number of features introduced in 4.1.0
38 * such as the new autoglobals.
39 */
40 if( !function_exists('iconv') ) {
41 # iconv support is not in the default configuration and so may not be present.
42 # Assume will only ever use utf-8 and iso-8859-1.
43 # This will *not* work in all circumstances.
44 function iconv( $from, $to, $string ) {
45 if(strcasecmp( $from, $to ) == 0) return $string;
46 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
47 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
48 return $string;
49 }
50 }
51
52 if( !function_exists('file_get_contents') ) {
53 # Exists in PHP 4.3.0+
54 function file_get_contents( $filename ) {
55 return implode( '', file( $filename ) );
56 }
57 }
58
59 if( !function_exists('is_a') ) {
60 # Exists in PHP 4.2.0+
61 function is_a( $object, $class_name ) {
62 return
63 (strcasecmp( get_class( $object ), $class_name ) == 0) ||
64 is_subclass_of( $object, $class_name );
65 }
66 }
67
68 # UTF-8 substr function based on a PHP manual comment
69 if ( !function_exists( 'mb_substr' ) ) {
70 function mb_substr( $str, $start ) {
71 preg_match_all( '/./us', $str, $ar );
72
73 if( func_num_args() >= 3 ) {
74 $end = func_get_arg( 2 );
75 return join( '', array_slice( $ar[0], $start, $end ) );
76 } else {
77 return join( '', array_slice( $ar[0], $start ) );
78 }
79 }
80 }
81
82 if( !function_exists( 'floatval' ) ) {
83 /**
84 * First defined in PHP 4.2.0
85 * @param mixed $var;
86 * @return float
87 */
88 function floatval( $var ) {
89 return (float)$var;
90 }
91 }
92
93 /**
94 * Where as we got a random seed
95 * @var bool $wgTotalViews
96 */
97 $wgRandomSeeded = false;
98
99 /**
100 * Seed Mersenne Twister
101 * Only necessary in PHP < 4.2.0
102 *
103 * @return bool
104 */
105 function wfSeedRandom() {
106 global $wgRandomSeeded;
107
108 if ( ! $wgRandomSeeded && version_compare( phpversion(), '4.2.0' ) < 0 ) {
109 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
110 mt_srand( $seed );
111 $wgRandomSeeded = true;
112 }
113 }
114
115 /**
116 * Get a random decimal value between 0 and 1, in a way
117 * not likely to give duplicate values for any realistic
118 * number of articles.
119 *
120 * @return string
121 */
122 function wfRandom() {
123 # The maximum random value is "only" 2^31-1, so get two random
124 # values to reduce the chance of dupes
125 $max = mt_getrandmax();
126 $rand = number_format( (mt_rand() * $max + mt_rand())
127 / $max / $max, 12, '.', '' );
128 return $rand;
129 }
130
131 /**
132 * We want / and : to be included as literal characters in our title URLs.
133 * %2F in the page titles seems to fatally break for some reason.
134 *
135 * @param string $s
136 * @return string
137 */
138 function wfUrlencode ( $s ) {
139 $s = urlencode( $s );
140 $s = preg_replace( '/%3[Aa]/', ':', $s );
141 $s = preg_replace( '/%2[Ff]/', '/', $s );
142
143 return $s;
144 }
145
146 /**
147 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
148 * In normal operation this is a NOP.
149 *
150 * Controlling globals:
151 * $wgDebugLogFile - points to the log file
152 * $wgProfileOnly - if set, normal debug messages will not be recorded.
153 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
154 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
155 *
156 * @param string $text
157 * @param bool $logonly Set true to avoid appearing in HTML when $wgDebugComments is set
158 */
159 function wfDebug( $text, $logonly = false ) {
160 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
161
162 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
163 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
164 return;
165 }
166
167 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
168 $wgOut->debug( $text );
169 }
170 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
171 # Strip unprintables; they can switch terminal modes when binary data
172 # gets dumped, which is pretty annoying.
173 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
174 @error_log( $text, 3, $wgDebugLogFile );
175 }
176 }
177
178 /**
179 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
180 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
181 *
182 * @param string $logGroup
183 * @param string $text
184 * @param bool $public Whether to log the event in the public log if no private
185 * log file is specified, (default true)
186 */
187 function wfDebugLog( $logGroup, $text, $public = true ) {
188 global $wgDebugLogGroups, $wgDBname;
189 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
190 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
191 @error_log( "$wgDBname: $text", 3, $wgDebugLogGroups[$logGroup] );
192 } else if ( $public === true ) {
193 wfDebug( $text, true );
194 }
195 }
196
197 /**
198 * Log for database errors
199 * @param string $text Database error message.
200 */
201 function wfLogDBError( $text ) {
202 global $wgDBerrorLog;
203 if ( $wgDBerrorLog ) {
204 $host = trim(`hostname`);
205 $text = date('D M j G:i:s T Y') . "\t$host\t".$text;
206 error_log( $text, 3, $wgDBerrorLog );
207 }
208 }
209
210 /**
211 * @todo document
212 */
213 function logProfilingData() {
214 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
215 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
216 $now = wfTime();
217
218 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
219 $start = (float)$sec + (float)$usec;
220 $elapsed = $now - $start;
221 if ( $wgProfiling ) {
222 $prof = wfGetProfilingOutput( $start, $elapsed );
223 $forward = '';
224 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
225 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
226 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
227 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
228 if( !empty( $_SERVER['HTTP_FROM'] ) )
229 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
230 if( $forward )
231 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
232 if( $wgUser->isAnon() )
233 $forward .= ' anon';
234 $log = sprintf( "%s\t%04.3f\t%s\n",
235 gmdate( 'YmdHis' ), $elapsed,
236 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
237 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' || $wgDebugRawPage ) ) {
238 error_log( $log . $prof, 3, $wgDebugLogFile );
239 }
240 }
241 }
242
243 /**
244 * Check if the wiki read-only lock file is present. This can be used to lock
245 * off editing functions, but doesn't guarantee that the database will not be
246 * modified.
247 * @return bool
248 */
249 function wfReadOnly() {
250 global $wgReadOnlyFile, $wgReadOnly;
251
252 if ( $wgReadOnly ) {
253 return true;
254 }
255 if ( '' == $wgReadOnlyFile ) {
256 return false;
257 }
258
259 // Set $wgReadOnly and unset $wgReadOnlyFile, for faster access next time
260 if ( is_file( $wgReadOnlyFile ) ) {
261 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
262 } else {
263 $wgReadOnly = false;
264 }
265 $wgReadOnlyFile = '';
266 return $wgReadOnly;
267 }
268
269
270 /**
271 * Get a message from anywhere, for the current user language.
272 *
273 * Use wfMsgForContent() instead if the message should NOT
274 * change depending on the user preferences.
275 *
276 * Note that the message may contain HTML, and is therefore
277 * not safe for insertion anywhere. Some functions such as
278 * addWikiText will do the escaping for you. Use wfMsgHtml()
279 * if you need an escaped message.
280 *
281 * @param string lookup key for the message, usually
282 * defined in languages/Language.php
283 */
284 function wfMsg( $key ) {
285 $args = func_get_args();
286 array_shift( $args );
287 return wfMsgReal( $key, $args, true );
288 }
289
290 /**
291 * Same as above except doesn't transform the message
292 */
293 function wfMsgNoTrans( $key ) {
294 $args = func_get_args();
295 array_shift( $args );
296 return wfMsgReal( $key, $args, true, false );
297 }
298
299 /**
300 * Get a message from anywhere, for the current global language
301 * set with $wgLanguageCode.
302 *
303 * Use this if the message should NOT change dependent on the
304 * language set in the user's preferences. This is the case for
305 * most text written into logs, as well as link targets (such as
306 * the name of the copyright policy page). Link titles, on the
307 * other hand, should be shown in the UI language.
308 *
309 * Note that MediaWiki allows users to change the user interface
310 * language in their preferences, but a single installation
311 * typically only contains content in one language.
312 *
313 * Be wary of this distinction: If you use wfMsg() where you should
314 * use wfMsgForContent(), a user of the software may have to
315 * customize over 70 messages in order to, e.g., fix a link in every
316 * possible language.
317 *
318 * @param string lookup key for the message, usually
319 * defined in languages/Language.php
320 */
321 function wfMsgForContent( $key ) {
322 global $wgForceUIMsgAsContentMsg;
323 $args = func_get_args();
324 array_shift( $args );
325 $forcontent = true;
326 if( is_array( $wgForceUIMsgAsContentMsg ) &&
327 in_array( $key, $wgForceUIMsgAsContentMsg ) )
328 $forcontent = false;
329 return wfMsgReal( $key, $args, true, $forcontent );
330 }
331
332 /**
333 * Same as above except doesn't transform the message
334 */
335 function wfMsgForContentNoTrans( $key ) {
336 global $wgForceUIMsgAsContentMsg;
337 $args = func_get_args();
338 array_shift( $args );
339 $forcontent = true;
340 if( is_array( $wgForceUIMsgAsContentMsg ) &&
341 in_array( $key, $wgForceUIMsgAsContentMsg ) )
342 $forcontent = false;
343 return wfMsgReal( $key, $args, true, $forcontent, false );
344 }
345
346 /**
347 * Get a message from the language file, for the UI elements
348 */
349 function wfMsgNoDB( $key ) {
350 $args = func_get_args();
351 array_shift( $args );
352 return wfMsgReal( $key, $args, false );
353 }
354
355 /**
356 * Get a message from the language file, for the content
357 */
358 function wfMsgNoDBForContent( $key ) {
359 global $wgForceUIMsgAsContentMsg;
360 $args = func_get_args();
361 array_shift( $args );
362 $forcontent = true;
363 if( is_array( $wgForceUIMsgAsContentMsg ) &&
364 in_array( $key, $wgForceUIMsgAsContentMsg ) )
365 $forcontent = false;
366 return wfMsgReal( $key, $args, false, $forcontent );
367 }
368
369
370 /**
371 * Really get a message
372 */
373 function wfMsgReal( $key, $args, $useDB, $forContent=false, $transform = true ) {
374 $fname = 'wfMsgReal';
375 wfProfileIn( $fname );
376
377 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
378 $message = wfMsgReplaceArgs( $message, $args );
379 wfProfileOut( $fname );
380 return $message;
381 }
382
383 /**
384 * Fetch a message string value, but don't replace any keys yet.
385 * @param string $key
386 * @param bool $useDB
387 * @param bool $forContent
388 * @return string
389 * @access private
390 */
391 function wfMsgGetKey( $key, $useDB, $forContent = false, $transform = true ) {
392 global $wgParser, $wgMsgParserOptions;
393 global $wgContLang, $wgLanguageCode;
394 global $wgMessageCache, $wgLang;
395
396 $transstat = $wgMessageCache->getTransform();
397
398 if( is_object( $wgMessageCache ) ) {
399 if ( ! $transform )
400 $wgMessageCache->disableTransform();
401 $message = $wgMessageCache->get( $key, $useDB, $forContent );
402 } else {
403 if( $forContent ) {
404 $lang = &$wgContLang;
405 } else {
406 $lang = &$wgLang;
407 }
408
409 wfSuppressWarnings();
410
411 if( is_object( $lang ) ) {
412 $message = $lang->getMessage( $key );
413 } else {
414 $message = false;
415 }
416 wfRestoreWarnings();
417 if($message === false)
418 $message = Language::getMessage($key);
419 if ( $transform && strstr( $message, '{{' ) !== false ) {
420 $message = $wgParser->transformMsg($message, $wgMsgParserOptions);
421 }
422 }
423
424 if ( ! $transform )
425 $wgMessageCache->setTransform( $transstat );
426
427 return $message;
428 }
429
430 /**
431 * Replace message parameter keys on the given formatted output.
432 *
433 * @param string $message
434 * @param array $args
435 * @return string
436 * @access private
437 */
438 function wfMsgReplaceArgs( $message, $args ) {
439 # Fix windows line-endings
440 # Some messages are split with explode("\n", $msg)
441 $message = str_replace( "\r", '', $message );
442
443 // Replace arguments
444 if ( count( $args ) )
445 if ( is_array( $args[0] ) )
446 foreach ( $args[0] as $key => $val )
447 $message = str_replace( '$' . $key, $val, $message );
448 else {
449 foreach( $args as $n => $param )
450 $replacementKeys['$' . ($n + 1)] = $param;
451 $message = strtr( $message, $replacementKeys );
452 }
453
454 return $message;
455 }
456
457 /**
458 * Return an HTML-escaped version of a message.
459 * Parameter replacements, if any, are done *after* the HTML-escaping,
460 * so parameters may contain HTML (eg links or form controls). Be sure
461 * to pre-escape them if you really do want plaintext, or just wrap
462 * the whole thing in htmlspecialchars().
463 *
464 * @param string $key
465 * @param string ... parameters
466 * @return string
467 */
468 function wfMsgHtml( $key ) {
469 $args = func_get_args();
470 array_shift( $args );
471 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
472 }
473
474 /**
475 * Return an HTML version of message
476 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
477 * so parameters may contain HTML (eg links or form controls). Be sure
478 * to pre-escape them if you really do want plaintext, or just wrap
479 * the whole thing in htmlspecialchars().
480 *
481 * @param string $key
482 * @param string ... parameters
483 * @return string
484 */
485 function wfMsgWikiHtml( $key ) {
486 global $wgOut;
487 $args = func_get_args();
488 array_shift( $args );
489 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
490 }
491
492 /**
493 * Just like exit() but makes a note of it.
494 * Commits open transactions except if the error parameter is set
495 */
496 function wfAbruptExit( $error = false ){
497 global $wgLoadBalancer;
498 static $called = false;
499 if ( $called ){
500 exit();
501 }
502 $called = true;
503
504 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
505 $bt = debug_backtrace();
506 for($i = 0; $i < count($bt) ; $i++){
507 $file = isset($bt[$i]['file']) ? $bt[$i]['file'] : "unknown";
508 $line = isset($bt[$i]['line']) ? $bt[$i]['line'] : "unknown";
509 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
510 }
511 } else {
512 wfDebug('WARNING: Abrupt exit\n');
513 }
514 if ( !$error ) {
515 $wgLoadBalancer->closeAll();
516 }
517 exit();
518 }
519
520 /**
521 * @todo document
522 */
523 function wfErrorExit() {
524 wfAbruptExit( true );
525 }
526
527 /**
528 * Die with a backtrace
529 * This is meant as a debugging aid to track down where bad data comes from.
530 * Shouldn't be used in production code except maybe in "shouldn't happen" areas.
531 *
532 * @param string $msg Message shown when dieing.
533 */
534 function wfDebugDieBacktrace( $msg = '' ) {
535 global $wgCommandLineMode;
536
537 $backtrace = wfBacktrace();
538 if ( $backtrace !== false ) {
539 if ( $wgCommandLineMode ) {
540 $msg .= "\nBacktrace:\n$backtrace";
541 } else {
542 $msg .= "\n<p>Backtrace:</p>\n$backtrace";
543 }
544 }
545 echo $msg;
546 echo wfReportTime()."\n";
547 die( -1 );
548 }
549
550 /**
551 * Returns a HTML comment with the elapsed time since request.
552 * This method has no side effects.
553 * @return string
554 */
555 function wfReportTime() {
556 global $wgRequestTime;
557
558 $now = wfTime();
559 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
560 $start = (float)$sec + (float)$usec;
561 $elapsed = $now - $start;
562
563 # Use real server name if available, so we know which machine
564 # in a server farm generated the current page.
565 if ( function_exists( 'posix_uname' ) ) {
566 $uname = @posix_uname();
567 } else {
568 $uname = false;
569 }
570 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
571 $hostname = $uname['nodename'];
572 } else {
573 # This may be a virtual server.
574 $hostname = $_SERVER['SERVER_NAME'];
575 }
576 $com = sprintf( "<!-- Served by %s in %01.2f secs. -->",
577 $hostname, $elapsed );
578 return $com;
579 }
580
581 function wfBacktrace() {
582 global $wgCommandLineMode;
583 if ( !function_exists( 'debug_backtrace' ) ) {
584 return false;
585 }
586
587 if ( $wgCommandLineMode ) {
588 $msg = '';
589 } else {
590 $msg = "<ul>\n";
591 }
592 $backtrace = debug_backtrace();
593 foreach( $backtrace as $call ) {
594 if( isset( $call['file'] ) ) {
595 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
596 $file = $f[count($f)-1];
597 } else {
598 $file = '-';
599 }
600 if( isset( $call['line'] ) ) {
601 $line = $call['line'];
602 } else {
603 $line = '-';
604 }
605 if ( $wgCommandLineMode ) {
606 $msg .= "$file line $line calls ";
607 } else {
608 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
609 }
610 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
611 $msg .= $call['function'] . '()';
612
613 if ( $wgCommandLineMode ) {
614 $msg .= "\n";
615 } else {
616 $msg .= "</li>\n";
617 }
618 }
619 if ( $wgCommandLineMode ) {
620 $msg .= "\n";
621 } else {
622 $msg .= "</ul>\n";
623 }
624
625 return $msg;
626 }
627
628
629 /* Some generic result counters, pulled out of SearchEngine */
630
631
632 /**
633 * @todo document
634 */
635 function wfShowingResults( $offset, $limit ) {
636 global $wgLang;
637 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
638 }
639
640 /**
641 * @todo document
642 */
643 function wfShowingResultsNum( $offset, $limit, $num ) {
644 global $wgLang;
645 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
646 }
647
648 /**
649 * @todo document
650 */
651 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
652 global $wgUser, $wgLang;
653 $fmtLimit = $wgLang->formatNum( $limit );
654 $prev = wfMsg( 'prevn', $fmtLimit );
655 $next = wfMsg( 'nextn', $fmtLimit );
656
657 if( is_object( $link ) ) {
658 $title =& $link;
659 } else {
660 $title = Title::newFromText( $link );
661 if( is_null( $title ) ) {
662 return false;
663 }
664 }
665
666 $sk = $wgUser->getSkin();
667 if ( 0 != $offset ) {
668 $po = $offset - $limit;
669 if ( $po < 0 ) { $po = 0; }
670 $q = "limit={$limit}&offset={$po}";
671 if ( '' != $query ) { $q .= '&'.$query; }
672 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
673 } else { $plink = $prev; }
674
675 $no = $offset + $limit;
676 $q = 'limit='.$limit.'&offset='.$no;
677 if ( '' != $query ) { $q .= '&'.$query; }
678
679 if ( $atend ) {
680 $nlink = $next;
681 } else {
682 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
683 }
684 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
685 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
686 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
687 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
688 wfNumLink( $offset, 500, $title, $query );
689
690 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
691 }
692
693 /**
694 * @todo document
695 */
696 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
697 global $wgUser, $wgLang;
698 if ( '' == $query ) { $q = ''; }
699 else { $q = $query.'&'; }
700 $q .= 'limit='.$limit.'&offset='.$offset;
701
702 $fmtLimit = $wgLang->formatNum( $limit );
703 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
704 return $s;
705 }
706
707 /**
708 * @todo document
709 * @todo FIXME: we may want to blacklist some broken browsers
710 *
711 * @return bool Whereas client accept gzip compression
712 */
713 function wfClientAcceptsGzip() {
714 global $wgUseGzip;
715 if( $wgUseGzip ) {
716 # FIXME: we may want to blacklist some broken browsers
717 if( preg_match(
718 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
719 $_SERVER['HTTP_ACCEPT_ENCODING'],
720 $m ) ) {
721 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
722 wfDebug( " accepts gzip\n" );
723 return true;
724 }
725 }
726 return false;
727 }
728
729 /**
730 * Yay, more global functions!
731 */
732 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
733 global $wgRequest;
734 return $wgRequest->getLimitOffset( $deflimit, $optionname );
735 }
736
737 /**
738 * Escapes the given text so that it may be output using addWikiText()
739 * without any linking, formatting, etc. making its way through. This
740 * is achieved by substituting certain characters with HTML entities.
741 * As required by the callers, <nowiki> is not used. It currently does
742 * not filter out characters which have special meaning only at the
743 * start of a line, such as "*".
744 *
745 * @param string $text Text to be escaped
746 */
747 function wfEscapeWikiText( $text ) {
748 $text = str_replace(
749 array( '[', '|', '\'', 'ISBN ' , '://' , "\n=", '{{' ),
750 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', '&#58;//' , "\n&#61;", '&#123;&#123;' ),
751 htmlspecialchars($text) );
752 return $text;
753 }
754
755 /**
756 * @todo document
757 */
758 function wfQuotedPrintable( $string, $charset = '' ) {
759 # Probably incomplete; see RFC 2045
760 if( empty( $charset ) ) {
761 global $wgInputEncoding;
762 $charset = $wgInputEncoding;
763 }
764 $charset = strtoupper( $charset );
765 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
766
767 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
768 $replace = $illegal . '\t ?_';
769 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
770 $out = "=?$charset?Q?";
771 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
772 $out .= '?=';
773 return $out;
774 }
775
776 /**
777 * Returns an escaped string suitable for inclusion in a string literal
778 * for JavaScript source code.
779 * Illegal control characters are assumed not to be present.
780 *
781 * @param string $string
782 * @return string
783 */
784 function wfEscapeJsString( $string ) {
785 // See ECMA 262 section 7.8.4 for string literal format
786 $pairs = array(
787 "\\" => "\\\\",
788 "\"" => "\\\"",
789 '\'' => '\\\'',
790 "\n" => "\\n",
791 "\r" => "\\r",
792
793 # To avoid closing the element or CDATA section
794 "<" => "\\x3c",
795 ">" => "\\x3e",
796 );
797 return strtr( $string, $pairs );
798 }
799
800 /**
801 * @todo document
802 * @return float
803 */
804 function wfTime() {
805 $st = explode( ' ', microtime() );
806 return (float)$st[0] + (float)$st[1];
807 }
808
809 /**
810 * Changes the first character to an HTML entity
811 */
812 function wfHtmlEscapeFirst( $text ) {
813 $ord = ord($text);
814 $newText = substr($text, 1);
815 return "&#$ord;$newText";
816 }
817
818 /**
819 * Sets dest to source and returns the original value of dest
820 * If source is NULL, it just returns the value, it doesn't set the variable
821 */
822 function wfSetVar( &$dest, $source ) {
823 $temp = $dest;
824 if ( !is_null( $source ) ) {
825 $dest = $source;
826 }
827 return $temp;
828 }
829
830 /**
831 * As for wfSetVar except setting a bit
832 */
833 function wfSetBit( &$dest, $bit, $state = true ) {
834 $temp = (bool)($dest & $bit );
835 if ( !is_null( $state ) ) {
836 if ( $state ) {
837 $dest |= $bit;
838 } else {
839 $dest &= ~$bit;
840 }
841 }
842 return $temp;
843 }
844
845 /**
846 * This function takes two arrays as input, and returns a CGI-style string, e.g.
847 * "days=7&limit=100". Options in the first array override options in the second.
848 * Options set to "" will not be output.
849 */
850 function wfArrayToCGI( $array1, $array2 = NULL )
851 {
852 if ( !is_null( $array2 ) ) {
853 $array1 = $array1 + $array2;
854 }
855
856 $cgi = '';
857 foreach ( $array1 as $key => $value ) {
858 if ( '' !== $value ) {
859 if ( '' != $cgi ) {
860 $cgi .= '&';
861 }
862 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
863 }
864 }
865 return $cgi;
866 }
867
868 /**
869 * This is obsolete, use SquidUpdate::purge()
870 * @deprecated
871 */
872 function wfPurgeSquidServers ($urlArr) {
873 SquidUpdate::purge( $urlArr );
874 }
875
876 /**
877 * Windows-compatible version of escapeshellarg()
878 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
879 * function puts single quotes in regardless of OS
880 */
881 function wfEscapeShellArg( ) {
882 $args = func_get_args();
883 $first = true;
884 $retVal = '';
885 foreach ( $args as $arg ) {
886 if ( !$first ) {
887 $retVal .= ' ';
888 } else {
889 $first = false;
890 }
891
892 if ( wfIsWindows() ) {
893 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
894 } else {
895 $retVal .= escapeshellarg( $arg );
896 }
897 }
898 return $retVal;
899 }
900
901 /**
902 * wfMerge attempts to merge differences between three texts.
903 * Returns true for a clean merge and false for failure or a conflict.
904 */
905 function wfMerge( $old, $mine, $yours, &$result ){
906 global $wgDiff3;
907
908 # This check may also protect against code injection in
909 # case of broken installations.
910 if(! file_exists( $wgDiff3 ) ){
911 wfDebug( "diff3 not found\n" );
912 return false;
913 }
914
915 # Make temporary files
916 $td = wfTempDir();
917 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
918 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
919 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
920
921 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
922 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
923 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
924
925 # Check for a conflict
926 $cmd = $wgDiff3 . ' -a --overlap-only ' .
927 wfEscapeShellArg( $mytextName ) . ' ' .
928 wfEscapeShellArg( $oldtextName ) . ' ' .
929 wfEscapeShellArg( $yourtextName );
930 $handle = popen( $cmd, 'r' );
931
932 if( fgets( $handle, 1024 ) ){
933 $conflict = true;
934 } else {
935 $conflict = false;
936 }
937 pclose( $handle );
938
939 # Merge differences
940 $cmd = $wgDiff3 . ' -a -e --merge ' .
941 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
942 $handle = popen( $cmd, 'r' );
943 $result = '';
944 do {
945 $data = fread( $handle, 8192 );
946 if ( strlen( $data ) == 0 ) {
947 break;
948 }
949 $result .= $data;
950 } while ( true );
951 pclose( $handle );
952 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
953
954 if ( $result === '' && $old !== '' && $conflict == false ) {
955 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
956 $conflict = true;
957 }
958 return ! $conflict;
959 }
960
961 /**
962 * @todo document
963 */
964 function wfVarDump( $var ) {
965 global $wgOut;
966 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
967 if ( headers_sent() || !@is_object( $wgOut ) ) {
968 print $s;
969 } else {
970 $wgOut->addHTML( $s );
971 }
972 }
973
974 /**
975 * Provide a simple HTTP error.
976 */
977 function wfHttpError( $code, $label, $desc ) {
978 global $wgOut;
979 $wgOut->disable();
980 header( "HTTP/1.0 $code $label" );
981 header( "Status: $code $label" );
982 $wgOut->sendCacheControl();
983
984 header( 'Content-type: text/html' );
985 print "<html><head><title>" .
986 htmlspecialchars( $label ) .
987 "</title></head><body><h1>" .
988 htmlspecialchars( $label ) .
989 "</h1><p>" .
990 htmlspecialchars( $desc ) .
991 "</p></body></html>\n";
992 }
993
994 /**
995 * Converts an Accept-* header into an array mapping string values to quality
996 * factors
997 */
998 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
999 # No arg means accept anything (per HTTP spec)
1000 if( !$accept ) {
1001 return array( $def => 1 );
1002 }
1003
1004 $prefs = array();
1005
1006 $parts = explode( ',', $accept );
1007
1008 foreach( $parts as $part ) {
1009 # FIXME: doesn't deal with params like 'text/html; level=1'
1010 @list( $value, $qpart ) = explode( ';', $part );
1011 if( !isset( $qpart ) ) {
1012 $prefs[$value] = 1;
1013 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1014 $prefs[$value] = $match[1];
1015 }
1016 }
1017
1018 return $prefs;
1019 }
1020
1021 /**
1022 * Checks if a given MIME type matches any of the keys in the given
1023 * array. Basic wildcards are accepted in the array keys.
1024 *
1025 * Returns the matching MIME type (or wildcard) if a match, otherwise
1026 * NULL if no match.
1027 *
1028 * @param string $type
1029 * @param array $avail
1030 * @return string
1031 * @access private
1032 */
1033 function mimeTypeMatch( $type, $avail ) {
1034 if( array_key_exists($type, $avail) ) {
1035 return $type;
1036 } else {
1037 $parts = explode( '/', $type );
1038 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1039 return $parts[0] . '/*';
1040 } elseif( array_key_exists( '*/*', $avail ) ) {
1041 return '*/*';
1042 } else {
1043 return NULL;
1044 }
1045 }
1046 }
1047
1048 /**
1049 * Returns the 'best' match between a client's requested internet media types
1050 * and the server's list of available types. Each list should be an associative
1051 * array of type to preference (preference is a float between 0.0 and 1.0).
1052 * Wildcards in the types are acceptable.
1053 *
1054 * @param array $cprefs Client's acceptable type list
1055 * @param array $sprefs Server's offered types
1056 * @return string
1057 *
1058 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1059 * XXX: generalize to negotiate other stuff
1060 */
1061 function wfNegotiateType( $cprefs, $sprefs ) {
1062 $combine = array();
1063
1064 foreach( array_keys($sprefs) as $type ) {
1065 $parts = explode( '/', $type );
1066 if( $parts[1] != '*' ) {
1067 $ckey = mimeTypeMatch( $type, $cprefs );
1068 if( $ckey ) {
1069 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1070 }
1071 }
1072 }
1073
1074 foreach( array_keys( $cprefs ) as $type ) {
1075 $parts = explode( '/', $type );
1076 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1077 $skey = mimeTypeMatch( $type, $sprefs );
1078 if( $skey ) {
1079 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1080 }
1081 }
1082 }
1083
1084 $bestq = 0;
1085 $besttype = NULL;
1086
1087 foreach( array_keys( $combine ) as $type ) {
1088 if( $combine[$type] > $bestq ) {
1089 $besttype = $type;
1090 $bestq = $combine[$type];
1091 }
1092 }
1093
1094 return $besttype;
1095 }
1096
1097 /**
1098 * Array lookup
1099 * Returns an array where the values in the first array are replaced by the
1100 * values in the second array with the corresponding keys
1101 *
1102 * @return array
1103 */
1104 function wfArrayLookup( $a, $b ) {
1105 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1106 }
1107
1108 /**
1109 * Convenience function; returns MediaWiki timestamp for the present time.
1110 * @return string
1111 */
1112 function wfTimestampNow() {
1113 # return NOW
1114 return wfTimestamp( TS_MW, time() );
1115 }
1116
1117 /**
1118 * Reference-counted warning suppression
1119 */
1120 function wfSuppressWarnings( $end = false ) {
1121 static $suppressCount = 0;
1122 static $originalLevel = false;
1123
1124 if ( $end ) {
1125 if ( $suppressCount ) {
1126 --$suppressCount;
1127 if ( !$suppressCount ) {
1128 error_reporting( $originalLevel );
1129 }
1130 }
1131 } else {
1132 if ( !$suppressCount ) {
1133 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
1134 }
1135 ++$suppressCount;
1136 }
1137 }
1138
1139 /**
1140 * Restore error level to previous value
1141 */
1142 function wfRestoreWarnings() {
1143 wfSuppressWarnings( true );
1144 }
1145
1146 # Autodetect, convert and provide timestamps of various types
1147
1148 /**
1149 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1150 */
1151 define('TS_UNIX', 0);
1152
1153 /**
1154 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1155 */
1156 define('TS_MW', 1);
1157
1158 /**
1159 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1160 */
1161 define('TS_DB', 2);
1162
1163 /**
1164 * RFC 2822 format, for E-mail and HTTP headers
1165 */
1166 define('TS_RFC2822', 3);
1167
1168 /**
1169 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1170 *
1171 * This is used by Special:Export
1172 */
1173 define('TS_ISO_8601', 4);
1174
1175 /**
1176 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1177 *
1178 * @link http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1179 * DateTime tag and page 36 for the DateTimeOriginal and
1180 * DateTimeDigitized tags.
1181 */
1182 define('TS_EXIF', 5);
1183
1184 /**
1185 * Oracle format time.
1186 */
1187 define('TS_ORACLE', 6);
1188
1189 /**
1190 * @param mixed $outputtype A timestamp in one of the supported formats, the
1191 * function will autodetect which format is supplied
1192 and act accordingly.
1193 * @return string Time in the format specified in $outputtype
1194 */
1195 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1196 $uts = 0;
1197 if ($ts==0) {
1198 $uts=time();
1199 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1200 # TS_DB
1201 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1202 (int)$da[2],(int)$da[3],(int)$da[1]);
1203 } elseif (preg_match("/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1204 # TS_EXIF
1205 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1206 (int)$da[2],(int)$da[3],(int)$da[1]);
1207 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1208 # TS_MW
1209 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1210 (int)$da[2],(int)$da[3],(int)$da[1]);
1211 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1212 # TS_UNIX
1213 $uts=$ts;
1214 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1215 # TS_ORACLE
1216 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1217 str_replace("+00:00", "UTC", $ts)));
1218 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1219 # TS_ISO_8601
1220 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1221 (int)$da[2],(int)$da[3],(int)$da[1]);
1222 } else {
1223 # Bogus value; fall back to the epoch...
1224 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1225 $uts = 0;
1226 }
1227
1228
1229 switch($outputtype) {
1230 case TS_UNIX:
1231 return $uts;
1232 case TS_MW:
1233 return gmdate( 'YmdHis', $uts );
1234 case TS_DB:
1235 return gmdate( 'Y-m-d H:i:s', $uts );
1236 case TS_ISO_8601:
1237 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1238 // This shouldn't ever be used, but is included for completeness
1239 case TS_EXIF:
1240 return gmdate( 'Y:m:d H:i:s', $uts );
1241 case TS_RFC2822:
1242 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1243 case TS_ORACLE:
1244 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1245 default:
1246 wfDebugDieBacktrace( 'wfTimestamp() called with illegal output type.');
1247 }
1248 }
1249
1250 /**
1251 * Return a formatted timestamp, or null if input is null.
1252 * For dealing with nullable timestamp columns in the database.
1253 * @param int $outputtype
1254 * @param string $ts
1255 * @return string
1256 */
1257 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1258 if( is_null( $ts ) ) {
1259 return null;
1260 } else {
1261 return wfTimestamp( $outputtype, $ts );
1262 }
1263 }
1264
1265 /**
1266 * Check where as the operating system is Windows
1267 *
1268 * @return bool True if it's windows, False otherwise.
1269 */
1270 function wfIsWindows() {
1271 if (substr(php_uname(), 0, 7) == 'Windows') {
1272 return true;
1273 } else {
1274 return false;
1275 }
1276 }
1277
1278 /**
1279 * Swap two variables
1280 */
1281 function swap( &$x, &$y ) {
1282 $z = $x;
1283 $x = $y;
1284 $y = $z;
1285 }
1286
1287 function wfGetSiteNotice() {
1288 global $wgSiteNotice, $wgTitle, $wgOut;
1289 $fname = 'wfGetSiteNotice';
1290 wfProfileIn( $fname );
1291
1292 $notice = wfMsg( 'sitenotice' );
1293 if( $notice == '&lt;sitenotice&gt;' || $notice == '-' ) {
1294 $notice = '';
1295 }
1296 if( $notice == '' ) {
1297 # We may also need to override a message with eg downtime info
1298 # FIXME: make this work!
1299 $notice = $wgSiteNotice;
1300 }
1301 if($notice != '-' && $notice != '') {
1302 $specialparser = new Parser();
1303 $parserOutput = $specialparser->parse( $notice, $wgTitle, $wgOut->mParserOptions, false );
1304 $notice = $parserOutput->getText();
1305 }
1306 wfProfileOut( $fname );
1307 return $notice;
1308 }
1309
1310 /**
1311 * Format an XML element with given attributes and, optionally, text content.
1312 * Element and attribute names are assumed to be ready for literal inclusion.
1313 * Strings are assumed to not contain XML-illegal characters; special
1314 * characters (<, >, &) are escaped but illegals are not touched.
1315 *
1316 * @param string $element
1317 * @param array $attribs Name=>value pairs. Values will be escaped.
1318 * @param string $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1319 * @return string
1320 */
1321 function wfElement( $element, $attribs = null, $contents = '') {
1322 $out = '<' . $element;
1323 if( !is_null( $attribs ) ) {
1324 foreach( $attribs as $name => $val ) {
1325 $out .= ' ' . $name . '="' . htmlspecialchars( $val ) . '"';
1326 }
1327 }
1328 if( is_null( $contents ) ) {
1329 $out .= '>';
1330 } else {
1331 if( $contents == '' ) {
1332 $out .= ' />';
1333 } else {
1334 $out .= '>';
1335 $out .= htmlspecialchars( $contents );
1336 $out .= "</$element>";
1337 }
1338 }
1339 return $out;
1340 }
1341
1342 /**
1343 * Format an XML element as with wfElement(), but run text through the
1344 * UtfNormal::cleanUp() validator first to ensure that no invalid UTF-8
1345 * is passed.
1346 *
1347 * @param string $element
1348 * @param array $attribs Name=>value pairs. Values will be escaped.
1349 * @param string $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1350 * @return string
1351 */
1352 function wfElementClean( $element, $attribs = array(), $contents = '') {
1353 if( $attribs ) {
1354 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
1355 }
1356 if( $contents ) {
1357 $contents = UtfNormal::cleanUp( $contents );
1358 }
1359 return wfElement( $element, $attribs, $contents );
1360 }
1361
1362 // Shortcuts
1363 function wfOpenElement( $element ) { return "<$element>"; }
1364 function wfCloseElement( $element ) { return "</$element>"; }
1365
1366 /**
1367 * Create a namespace selector
1368 *
1369 * @param mixed $selected The namespace which should be selected, default ''
1370 * @param string $allnamespaces Value of a special item denoting all namespaces. Null to not include (default)
1371 * @return Html string containing the namespace selector
1372 */
1373 function &HTMLnamespaceselector($selected = '', $allnamespaces = null) {
1374 global $wgContLang;
1375 if( $selected !== '' ) {
1376 if( is_null( $selected ) ) {
1377 // No namespace selected; let exact match work without hitting Main
1378 $selected = '';
1379 } else {
1380 // Let input be numeric strings without breaking the empty match.
1381 $selected = intval( $selected );
1382 }
1383 }
1384 $s = "<select name='namespace' class='namespaceselector'>\n\t";
1385 $arr = $wgContLang->getFormattedNamespaces();
1386 if( !is_null($allnamespaces) ) {
1387 $arr = array($allnamespaces => wfMsgHtml('namespacesall')) + $arr;
1388 }
1389 foreach ($arr as $index => $name) {
1390 if ($index < NS_MAIN) continue;
1391
1392 $name = $index !== 0 ? $name : wfMsgHtml('blanknamespace');
1393
1394 if ($index === $selected) {
1395 $s .= wfElement("option",
1396 array("value" => $index, "selected" => "selected"),
1397 $name);
1398 } else {
1399 $s .= wfElement("option", array("value" => $index), $name);
1400 }
1401 }
1402 $s .= "\n</select>\n";
1403 return $s;
1404 }
1405
1406 /** Global singleton instance of MimeMagic. This is initialized on demand,
1407 * please always use the wfGetMimeMagic() function to get the instance.
1408 *
1409 * @private
1410 */
1411 $wgMimeMagic= NULL;
1412
1413 /** Factory functions for the global MimeMagic object.
1414 * This function always returns the same singleton instance of MimeMagic.
1415 * That objects will be instantiated on the first call to this function.
1416 * If needed, the MimeMagic.php file is automatically included by this function.
1417 * @return MimeMagic the global MimeMagic objects.
1418 */
1419 function &wfGetMimeMagic() {
1420 global $wgMimeMagic;
1421
1422 if (!is_null($wgMimeMagic)) {
1423 return $wgMimeMagic;
1424 }
1425
1426 if (!class_exists("MimeMagic")) {
1427 #include on demand
1428 require_once("MimeMagic.php");
1429 }
1430
1431 $wgMimeMagic= new MimeMagic();
1432
1433 return $wgMimeMagic;
1434 }
1435
1436
1437 /**
1438 * Tries to get the system directory for temporary files.
1439 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1440 * and if none are set /tmp is returned as the generic Unix default.
1441 *
1442 * NOTE: When possible, use the tempfile() function to create temporary
1443 * files to avoid race conditions on file creation, etc.
1444 *
1445 * @return string
1446 */
1447 function wfTempDir() {
1448 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1449 $tmp = getenv( $var );
1450 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1451 return $tmp;
1452 }
1453 }
1454 # Hope this is Unix of some kind!
1455 return '/tmp';
1456 }
1457
1458 /**
1459 * Make directory, and make all parent directories if they don't exist
1460 */
1461 function wfMkdirParents( $fullDir, $mode ) {
1462 $parts = explode( '/', $fullDir );
1463 $path = '';
1464
1465 foreach ( $parts as $dir ) {
1466 $path .= $dir . '/';
1467 if ( !is_dir( $path ) ) {
1468 if ( !mkdir( $path, $mode ) ) {
1469 return false;
1470 }
1471 }
1472 }
1473 return true;
1474 }
1475
1476 /**
1477 * Increment a statistics counter
1478 */
1479 function wfIncrStats( $key ) {
1480 global $wgDBname, $wgMemc;
1481 $key = "$wgDBname:stats:$key";
1482 if ( is_null( $wgMemc->incr( $key ) ) ) {
1483 $wgMemc->add( $key, 1 );
1484 }
1485 }
1486
1487 /**
1488 * @param mixed $nr The number to format
1489 * @param int $acc The number of digits after the decimal point, default 2
1490 * @param bool $round Whether or not to round the value, default true
1491 * @return float
1492 */
1493 function wfPercent( $nr, $acc = 2, $round = true ) {
1494 $ret = sprintf( "%.${acc}f", $nr );
1495 return $round ? round( $ret, $acc ) . '%' : "$ret%";
1496 }
1497
1498 /**
1499 * Encrypt a username/password.
1500 *
1501 * @param string $userid ID of the user
1502 * @param string $password Password of the user
1503 * @return string Hashed password
1504 */
1505 function wfEncryptPassword( $userid, $password ) {
1506 global $wgPasswordSalt;
1507 $p = md5( $password);
1508
1509 if($wgPasswordSalt)
1510 return md5( "{$userid}-{$p}" );
1511 else
1512 return $p;
1513 }
1514
1515 /**
1516 * Appends to second array if $value differs from that in $default
1517 */
1518 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1519 if ( is_null( $changed ) ) {
1520 wfDebugDieBacktrace('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1521 }
1522 if ( $default[$key] !== $value ) {
1523 $changed[$key] = $value;
1524 }
1525 }
1526
1527 /**
1528 * Since wfMsg() and co suck, they don't return false if the message key they
1529 * looked up didn't exist but a XHTML string, this function checks for the
1530 * nonexistance of messages by looking at wfMsg() output
1531 *
1532 * @param $msg The message key looked up
1533 * @param $wfMsgOut The output of wfMsg*()
1534 * @return bool
1535 */
1536 function wfEmptyMsg( $msg, $wfMsgOut ) {
1537 return $wfMsgOut === "&lt;$msg&gt;";
1538 }
1539
1540 /**
1541 * Find out whether or not a mixed variable exists in a string
1542 *
1543 * @param mixed needle
1544 * @param string haystack
1545 * @return bool
1546 */
1547 function in_string( $needle, $str ) {
1548 return strpos( $str, $needle ) !== false;
1549 }
1550
1551 /**
1552 * Returns a regular expression of url protocols
1553 *
1554 * @return string
1555 */
1556 function wfUrlProtocols() {
1557 global $wgUrlProtocols;
1558
1559 $x = array();
1560 foreach ($wgUrlProtocols as $protocol)
1561 $x[] = preg_quote( $protocol, '/' );
1562
1563 return implode( '|', $x );
1564 }
1565
1566 /**
1567 * Check if a string is well-formed XML.
1568 * Must include the surrounding tag.
1569 *
1570 * @param string $text
1571 * @return bool
1572 *
1573 * @todo Error position reporting return
1574 */
1575 function wfIsWellFormedXml( $text ) {
1576 $parser = xml_parser_create( "UTF-8" );
1577
1578 # case folding violates XML standard, turn it off
1579 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1580
1581 if( !xml_parse( $parser, $text, true ) ) {
1582 $err = xml_error_string( xml_get_error_code( $parser ) );
1583 $position = xml_get_current_byte_index( $parser );
1584 //$fragment = $this->extractFragment( $html, $position );
1585 //$this->mXmlError = "$err at byte $position:\n$fragment";
1586 xml_parser_free( $parser );
1587 return false;
1588 }
1589 xml_parser_free( $parser );
1590 return true;
1591 }
1592
1593 /**
1594 * Check if a string is a well-formed XML fragment.
1595 * Wraps fragment in an <html> bit and doctype, so it can be a fragment
1596 * and can use HTML named entities.
1597 *
1598 * @param string $text
1599 * @return bool
1600 */
1601 function wfIsWellFormedXmlFragment( $text ) {
1602 $html =
1603 '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ' .
1604 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' .
1605 '<html>' .
1606 $text .
1607 '</html>';
1608 return wfIsWellFormedXml( $html );
1609 }
1610
1611 /**
1612 * shell_exec() with time and memory limits mirrored from the PHP configuration,
1613 * if supported.
1614 */
1615 function wfShellExec( $cmd )
1616 {
1617 global $IP;
1618
1619 if ( php_uname( 's' ) == 'Linux' ) {
1620 $time = ini_get( 'max_execution_time' );
1621 $mem = ini_get( 'memory_limit' );
1622 if( preg_match( '/^([0-9]+)[Mm]$/', trim( $mem ), $m ) ) {
1623 $mem = intval( $m[1] * (1024*1024) );
1624 }
1625 if ( $time > 0 && $mem > 0 ) {
1626 $script = "$IP/bin/ulimit.sh";
1627 if ( is_executable( $script ) ) {
1628 $memKB = intval( $mem / 1024 );
1629 $cmd = escapeshellarg( $script ) . " $time $memKB $cmd";
1630 }
1631 }
1632 }
1633 return shell_exec( $cmd );
1634 }
1635
1636 ?>